package com.yik.countforcockpit.scheduler;

import com.yik.countforcockpit.entity.MetricDTO;
import com.yik.countforcockpit.service.MetricService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class MetricScheduler {

    @Autowired
    private  MetricService metricService;

    @Scheduled(cron = "0 */1 * * * ?")
    public void countForCockpitScheduler() {
        log.info("定时任务执行: {}", LocalDateTime.now());
        List<MetricDTO> metricDTOList = metricService.getAllMetrics();
        try {
            for (MetricDTO metricDTO : metricDTOList) {
                log.info("-----开始计算：{}",metricDTO.getMetricName());
                double v = metricService.handleMetric(metricDTO);
                metricDTO.setValue(v);
            }
        } catch (Exception e) {
            log.error("定时任务执行异常: {}", e.getMessage(), e);
        }
        // TODO: 2025/03/17 保存计算结果到数据库
        for (MetricDTO metricDTO : metricDTOList) {
            log.info("{} {} 结果为：{}{}",metricDTO.getMetricAttribute(), metricDTO.getMetricName(), metricDTO.getValue(), metricDTO.getUnit());
        }
        log.info("定时任务结束: {}", LocalDateTime.now());
    }
}
